<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 14/08/2017
 * Time: 17:34
 */

namespace common\models;

use common\models\ar\MoneyInOut;
use common\models\ar\User;
use common\models\ar\UserBrokers;
use common\models\ar\UserMoney;
use common\models\ar\UserMoneyChangerecord;
/**
 * 资金相关
 * Class MoneyDao
 * @package common\models
 */
class MoneyDao
{
    /**
     * 出入金操作
     *
     * @param $uidOperate
     * @param $uid
     * @param $direction
     * @param $money
     * @param $time
     * @param int $type 1为人工，2系统
     * @param string $ip
     * @param string $ua
     * @param string $remark
     *
     * @return bool
     */
    public static function inOut(
        $uidOperate,
        $uid,
        $direction,
        $money,
        $time,
        $type = 1,
        $ip = '',
        $ua = '',
        $remark = '',
        $dl=""
    ) {
        //资管平台
        $sql = "INSERT INTO `money_in_out` 
                  (`uid_operate`,`uid`,`money`,`time`,`direction`,`type`,`status`,`ip`,`ua`,`remark`,`response`) 
                VALUES
                 (:uid_operate,:uid,:money,:time,:direction,:type,:status,:ip,:ua,:remark,:response)
        ";

        $bool = \Yii::$app->db->createCommand($sql, [
            ':uid_operate' => $uidOperate,
            ':uid' => $uid,
            ':money' => $money,
            ':time' => $time,
            ':direction' => $direction,
            ':type' => $type,
            ':status' => 0,
            ':ip' => $ip,
            ':ua' => $ua,
            ':remark' => $remark,
            ':response' => '',
        ])->execute();

        if (!$bool) {
            return $bool;
        }
        $id = \Yii::$app->db->getLastInsertID();
        $recordObj = MoneyInOut::findOne(['id'=>$id]);
        //判断期权客户是否存在，不存在不能入金
        if ($dl=='1'){
            $tmp = UserBrokers::findOne(['id'=>$recordObj['uid']]);
            $tlevel=$tmp['level'];
        }else{
            $tmp = User::findOne(['userID'=>$recordObj['uid']]);
            $tlevel="";
        }
        if (!$tmp) {
            $return = ['code' => 0, 'msg' => '交易账户未开通'];
        } else {
            if ($tlevel!=""){
             $return = ['code' => 1, 'msg' => ''];
            }else{
            $return = self::tradeSystemInOut($uid, $money, $direction, $time,$tlevel);
            }
        }
        if ($return['code'] == 1) {
            $recordObj->status = 1;
        } else {
            $recordObj->status = 2;
            $recordObj->response = $return['msg'];
        }
        $recordObj->save(false);
        return $return['code'] == 1 ? true : false;
    }

    /**
     * 交易系统出入金
     *
     * @param $uid
     * @param $money
     * @param $direction
     * @param $time
     * @return array
     */
    public static function tradeSystemInOut($uid, $money, $direction, $time,$tlevel="")
    {
        $db = \Yii::$app->db;
        $sql="SELECT `user_money_change_id` FROM `money_withdraw` WHERE `status`=0 AND `userID`=:userID";
        $ids=$db->createCommand($sql, [
            ":userID" => $uid
        ])->queryOne();
        switch ($direction) {
            case 9://出金取消
                $times=UserMoneyChangerecord::findOne(['id'=>$ids['user_money_change_id']]);
                $times['changeTime'];
                $moneyChange = $money;
                $directionDesc = "提现申请取消时间:".$times['changeTime'];
                break;
            case 8://出金
                $moneyChange = -$money;
                $directionDesc = "提现申请：出金冻结";
                break;
//            case 15://手续费返现
//                $moneyChange = $money;
//                $directionDesc = "手续费返现：入金";
//                break;
//            case 16://出入金通道费
//                $moneyChange = -$money;
//                $directionDesc = "通道费：出金";
//                break;
            default:
                return ['code' => 0, 'msg' => '类型不正确'];
        }
        date_default_timezone_set("Asia/Shanghai");
        $date = date('Y-m-d H:i:s', $time);
        //获取当前user_money里面的资金明细
        $usermoney=UserMoney::findOne(['userID'=>$uid]);
        $transaction = $db->beginTransaction();
        try {
            if ($tlevel==""){
                //确认出金之后再user_money里面做资金变更
                $sql = "UPDATE  `user_money`
         SET
        `totalMoney` = `totalMoney`+:totalMoney
         WHERE `userID` = :userID
         ";
                $db->createCommand($sql, [
                    ":totalMoney" => $moneyChange,
                    ":userID" => $uid
                ])->execute();
                //当用户确认出金在user_money_changerecord里面写入流水记录
                $sql = "INSERT INTO `user_money_changerecord`
        (`userID`,`changeMoney`,`changeDesc`,`changeTime`,`type`,`tradeId`,`preTotalMoeny`,`preequip`)
         VALUES
        (:userID,:changeMoney,:changeDesc,:changeTime,:type,:tableid,:preTotalMoeny,:preequip)";

                $db->createCommand($sql, [
                    ':userID' => $uid,
                    ':changeMoney' => $moneyChange,
                    ':changeDesc' => $directionDesc,
                    ':changeTime' => $date,
                    ':type' => 2,
                    ':tableid'=>'0',
                    ':preTotalMoeny'=>$usermoney['totalMoney'],
                    ':preTotalMoney'=>$usermoney['totalMoney'],
                    ':preequip'=>$usermoney['equip']
                ])->execute();
                $sql="SELECT id FROM `user_money_changerecord` WHERE 
                  changeTime=(SELECT MAX(changeTime) FROM `user_money_changerecord` WHERE `userID`=:userID)";
                $extra_id=$db->createCommand($sql, [
                    ":userID" => $uid
                ])->queryAll();
                if($ids['user_money_change_id']==null){
                    $sql="UPDATE `money_withdraw` SET `user_money_change_id` = :extra_id WHERE `userID` = :userID";
                    $db->createCommand($sql, [
                        ":extra_id" => $extra_id[0]['id'],
                        ":userID" => $uid
                    ])->execute();
                }
            }
            //确认用户资金变更，记录到change_cache
            $sql = "INSERT INTO `change_cache` (`userid`,`change_type`,`extra_id`) values (:userID,:type,:extra_id)";
            if ($tlevel) {
                $db->createCommand($sql, [":userID" => $uid,":type"=>4,':extra_id'=>$extra_id[0]['id']])->execute();
            }else{
                $db->createCommand($sql, [":userID" =>$uid,":type"=>2,':extra_id'=>$extra_id[0]['id']])->execute();
            }
                $transaction->commit();
                $return = ['code' => 1, 'msg' => ''];
        } catch (\Exception $e) {
            $transaction->rollback();
            $return = ['code' => 0, 'msg' => $e->getTraceAsString()];
        }
        return $return;
    }

    /**
     * 资金变更历史
     *
     * @param int | array $direction
     * @param int $pid
     * @param int $pLevel
     * @param int $uid
     * @param int $start
     * @param int $end
     * @param int $pageNo
     * @param int $pageSize
     * @param array $orderByArr
     * @return array
     */
    public static function history(
        $direction = -1,
        $pid = -1,
        $pLevel = -1,
        $uid = -1,
        $start = -1,
        $end = -1,
        $pageNo = 1,
        $pageSize = 15,
        $orderByArr = ['time' => 'desc']
    ) {
        $db = \Yii::$app->db;

        $sql_count = "SELECT  COUNT(1) count,SUM(`money`) money FROM `money_change` a ";
        $sql_lists = "SELECT 
                        a.`userID`,
                        a.`money`,
                        a.`time`,
                        b.`loginName`,
                        b.`accountName`,
                        b.`userID`,
                        c.`name` direction
                      FROM  `money_change` a ";

        $sql_where = '';
        $sql_join = "LEFT JOIN `user` b ON b.`userID` = a.`userID` 
                     LEFT JOIN `money_change_direction` c ON c.`id` = a.`direction`
        ";
        $sql_orderBy = '';
        $sql_limit = " LIMIT " . ($pageNo - 1) * $pageSize . "," . $pageSize;

        $tmpWhere = [];
        $bind_arr = [];

        if ($uid != -1) {
            $tmpWhere[] = 'a.`userID` = :userID';
            $bind_arr[':userID'] = $uid;
        }

        if ($start != -1) {
            $tmpWhere[] = 'a.`time` >= :time_start';
            $bind_arr[':time_start'] = $start;
        }

        if ($end != -1) {
            //结束日期包含当天
            $tmpWhere[] = 'a.`time` < :time_end';
            $bind_arr[':time_end'] = $end;
        }

        if ($direction != -1) {
            //每级对应的可查看的资金类型
            $tmpWhere[] = 'a.`direction` in (' . implode(',', $direction) . ')';
        }

        if ($pid != -1) {
            $tmpWhere[] = 'b.`uid_level_' . $pLevel . '` = :pid';
            $bind_arr[':pid'] = $pid;
        }

        if (!empty($tmpWhere)) {
            $sql_where = 'WHERE ' . implode(' AND ', $tmpWhere);
        }

        $tmpOrderByArr = [];
        if (!empty($orderByArr)) {
            $sql_orderBy = " ORDER BY ";
            foreach ($orderByArr as $k => $v) {
                $tmpOrderByArr[] = "a.`" . $k . "` " . $v;
            }
            $sql_orderBy .= implode($tmpOrderByArr, ' , ');
        }

        $tmp = $db->createCommand($sql_count . $sql_join . $sql_where, $bind_arr)->queryOne();
        $lists = $db->createCommand(
            $sql_lists . $sql_join . $sql_where . $sql_orderBy . $sql_limit,
            $bind_arr
        )->queryAll();

        return [
            'total' => $tmp['count'] ? $tmp['count'] : 0,
            'sumMoney' => $tmp['money'] ? $tmp['money'] : 0,
            'lists' => $lists
        ];
    }
}
